package com.tjhq.commons.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

/**
 *
 * @author pc
 * @date 2017/12/5
 */
@ComponentScan
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class ApplicationConfig {
    private String url;
    private String username;
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String driver;
    
    // destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
    @Bean(destroyMethod = "close")
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driver);
        // 初始化时建立物理连接的个数
        dataSource.setInitialSize(2);
        // 最大连接池数量
        dataSource.setMaxActive(20);
        // 最小连接池数量
        dataSource.setMinIdle(0);
        // 获取连接时最大等待时间，单位毫秒。
        dataSource.setMaxWait(60000);
        // 用来检测连接是否有效的sql
        dataSource.setValidationQuery("SELECT 1");
        // 申请连接时执行validationQuery检测连接是否有效
        dataSource.setTestOnBorrow(false);
        // 建议配置为true，不影响性能，并且保证安全性。
        dataSource.setTestWhileIdle(true);
        // 是否缓存preparedStatement，也就是PSCache
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
    
    public String getUrl() {
        return url;
    }
    
    public void setUrl(String url) {
        this.url = url;
    }
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
}
